package com.prime;

import com.sun.swing.internal.plaf.synth.resources.synth_sv;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class RightPrimeChecker implements CanCheckIfPrime {
	private static final WrongIfPrimeChecker delegate = new WrongIfPrimeChecker();
    private static final ConcurrentHashMap<Integer,numberMonitor> numberMonitors = new ConcurrentHashMap<>();

	/**
	 * Thread safe!
	 * */
	@Override
	public boolean isPrime(int number) {
        Integer key = number;
        numberMonitors.putIfAbsent(key, new numberMonitor(number));

        boolean isPrime;
        numberMonitor nm = numberMonitors.get(key);
        //nm==null <=>some thread execute putIfAbsent(key,..) and then another thread remove(key)
        if( nm == null){
            isPrime = delegate.isPrime(number);
        } else synchronized (nm) {
            isPrime = delegate.isPrime(number);
        }
        numberMonitors.remove(key);

        return isPrime;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                RightPrimeChecker checker = new RightPrimeChecker();
                for(int i = Integer.MAX_VALUE; i > 2; i --){
                    checker.isPrime(i);
                }
            }
        };
        Thread t1 = new Thread(r), t2 = new Thread(r);
        t1.start();
        t2.start();
    }

    private class numberMonitor {
        private final int number;

        private numberMonitor(int number) {
            this.number = number;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof numberMonitor)) return false;

            numberMonitor numbermonitor = (numberMonitor) o;

            if (number != numbermonitor.number) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return number % 32;
        }

        @Override
        public String toString() {
            return "numberMonitor{" +
                    "number=" + number +
                    '}';
        }
    }
}
